//
//  TLMallWaterfallFlowViewController.m
//  WXReader
//
//  Created by huaya on 2025/1/13.
//  Copyright © 2025 Andrew. All rights reserved.
//

#import "TLMallWaterfallFlowViewController.h"
#import "XPCollectionViewWaterfallFlowLayout.h"
#import "TLMallWaterfallFlowCollectionViewCell.h"
#import "TLWaterfallFlowBannerCollectionViewCell.h"
#import "TLMallChannelModel.h"
#import "TLShortStoryViewController.h"

@interface TLMallWaterfallFlowViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,XPCollectionViewWaterfallFlowLayoutDataSource>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, assign) int pageNumb;
@property (nonatomic, assign) int pageSize;
@property (nonatomic, strong) NSMutableArray *dataArr;
@end

@implementation TLMallWaterfallFlowViewController
- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [NSMutableArray new];
    }
    return _dataArr;
}
- (void)resetFrame:(CGRect)frame{
    self.view.frame = frame;
    
    _collectionView.frame = CGRectMake(0, 0, frame.size.width, frame.size.height);
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.pageSize = 10;
    self.pageNumb = 1;
    [self.view addSubview:self.collectionView];
    [self network];
}
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        
        XPCollectionViewWaterfallFlowLayout *layout = [[XPCollectionViewWaterfallFlowLayout alloc] init];
        layout.dataSource = self;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.scrollEnabled = YES;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.frame = self.view.bounds;
        
        [self.view addSubview:_collectionView];
        [_collectionView registerClass:[TLMallWaterfallFlowCollectionViewCell class] forCellWithReuseIdentifier:@"TLMallWaterfallFlowCollectionViewCell"];
        
        [_collectionView registerNib:[UINib nibWithNibName:@"TLWaterfallFlowBannerCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"TLWaterfallFlowBannerCollectionViewCell"];
        [_collectionView registerClass:[UICollectionViewCell class]
            forCellWithReuseIdentifier:@"BlankCell"];
        
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadLastData)];
        header.lastUpdatedTimeLabel.hidden = YES;
        _collectionView.mj_header = header;
        
        _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        
    }
    return _collectionView;
}
- (void)loadMoreData{
    
    self.pageNumb = self.pageNumb + 1;
    
    [self network];
    
}
- (void)loadLastData{
    
    self.pageNumb = 1;
    [self network];
    
}
- (NSInteger)collectionView:(UICollectionView *)collectionView layout:(XPCollectionViewWaterfallFlowLayout*)layout numberOfColumnInSection:(NSInteger)section{
    
    if (MK_IS_PAD) {
        return 4;
    }else{
        return 2;
    }
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(XPCollectionViewWaterfallFlowLayout*)layout itemWidth:(CGFloat)width  heightForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row<self.dataArr.count) {
        
        TLMallChannelModel *model = self.dataArr[indexPath.row];
        if (model.showType.intValue == TLShowTypeBanner) {
            
            return 285;
        }else{
            return model.cellHeight;
        }
        
    }else{
        return 0;
    }
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {

    return 10;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 10;
}

#pragma mark - ***** UICollectionView delegate ******
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row<self.dataArr.count) {
        
        
        TLMallChannelModel *model = self.dataArr[indexPath.row];
        
        if ([model.showType intValue] == TLShowTypeBanner) {
            TLWaterfallFlowBannerCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TLWaterfallFlowBannerCollectionViewCell" forIndexPath:indexPath];
            
            cell.bannerList = model.bannerList;
            
            cell.layer.cornerRadius = 10;
            
            return cell;
        }else{
            
            TLMallWaterfallFlowCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TLMallWaterfallFlowCollectionViewCell" forIndexPath:indexPath];
            cell.model = model;
            cell.clipsToBounds = YES;
            cell.layer.masksToBounds = YES;
            cell.layer.cornerRadius = 10;
            MJWeakSelf
            cell.reloadCellBlock = ^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf reloadData:indexPath];
                });
            };
            
            return cell;
        }
            
    }else{
        UICollectionViewCell *blankCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BlankCell" forIndexPath:indexPath];
        blankCell.backgroundColor = [UIColor clearColor];
        blankCell.layer.masksToBounds = YES;
        return blankCell;
    }
}
- (void)reloadData:(NSIndexPath*)indexPath {
    // 主线程安全保护
    if (![NSThread isMainThread]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self reloadData:indexPath];
        });
        return;
    }
    
    // 有效性检查
    if (indexPath.row >= self.dataArr.count) return;
    
    // 执行局部刷新
    [self.collectionView performBatchUpdates:^{
        [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
    } completion:^(BOOL finished) {
        // 可选项：刷新后检查布局
        [self.collectionView.collectionViewLayout invalidateLayout];
    }];
}
// num
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return self.dataArr.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0);
}
//Select
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    TLMallChannelModel *model = self.dataArr[indexPath.row];
    
    if ([model.worksType isEqualToString:@"0"]) {
        //短篇
        TLShortStoryViewController *vc = [TLShortStoryViewController new];
        vc.worksId = model.worksId;
        [self.navigationController pushViewController:vc animated:YES];
        
    }else{
        //长篇
//        TL_BookMallDetailViewController *vc = [TL_BookMallDetailViewController new];
//        vc.book_id = [model.worksId intValue];
//        [self.navigationController pushViewController:vc animated:YES];
    }
    
}
- (void)network{
    
    [APIManager sendGetRequest:[APIURLManager queryOsWorksByChannel] parameters:@{@"channelId":@(self.channelId),@"pageNum":@(self.pageNumb),@"pageSize":@(self.pageSize)} model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        if (success) {
            if (self.pageNumb == 1) {
                [self.dataArr removeAllObjects];
            }
            NSArray *dataArr = [TLMallChannelModel mj_objectArrayWithKeyValuesArray:requestModel.data[@"records"]];
            
            [self.dataArr addObjectsFromArray:dataArr];
            
            [_collectionView reloadData];
            
            [self.collectionView.mj_header endRefreshing];
            [self.collectionView.mj_footer endRefreshing];
            
            if (dataArr.count<self.pageSize) {
                [self.collectionView.mj_footer endRefreshingWithNoMoreData];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        
        NSLog(@"123:%@",error);
        
    }];
    
}
@end
